package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Message;
import cn.wolfcode.trip.base.query.LetterQuery;
import cn.wolfcode.trip.base.service.ILetterService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

//私信
@RestController
@RequestMapping("/letters")
public class LetterController {

    @Autowired
    private ILetterService letterService;
    /**
     * 获取用户私信列表
     * @return
     */
    @GetMapping
    public PageInfo list(LetterQuery qo){
        qo.setPageSize(7);
        qo.setUserId(UserContext.getCurrentUser().getId());
        qo.setOrderBy("m.createTime desc");
        PageInfo pageInfo=letterService.queryForPage(qo);
        //更新私信状态为 已看过 状态
        letterService.updateLetterState(2,qo.getUserId());
        return pageInfo;
    }

    /**
     * 获取当前用户发送过的私信
     * @return
     */
    @GetMapping("/mysentLetters")
    public PageInfo mysentLetters(LetterQuery qo){
        qo.setPageSize(7);
        qo.setUserId(UserContext.getCurrentUser().getId());
        qo.setOrderBy("m.createTime desc");
        PageInfo pageInfo=letterService.querySentLettersForPage(qo);
        return pageInfo;
    }

    /**
     * 发送私信
     * @return
     */
    @PostMapping("/{reciverId}")
    public JSONResult sendLetters(Message letter, @PathVariable Long reciverId){
        JSONResult jsonResult=new JSONResult();
        try {
            letterService.sendLetters(letter,reciverId);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("error");
        }
        return jsonResult;
    }

    /**
     * 批量删除私信(实际上只是更新状态；不左物理删除)
     * @param ids
     * @param type 删除内容标识（DELETE_MY_RECIVE:代表删除我接收到的私信；DELETE_MY_SENT代表删除我发送的私信）
     * @return
     */
    @DeleteMapping("/{ids}/{type}")
    public JSONResult batshDelete(@PathVariable Long[] ids,@PathVariable String type){
        JSONResult jsonResult=new JSONResult();
        try {
            letterService.batshDelete(ids,type);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("error");
        }
        return jsonResult;
    }

    /**
     * 清空私信
     * @param type 清空内容标识（DELETE_MY_RECIVE:代表清空我接收到的私信；DELETE_MY_SENT代表清空我发送的私信）
     * @return
     */
    @DeleteMapping("/{type}")
    public JSONResult clearLetters(@PathVariable String type){
        JSONResult jsonResult=new JSONResult();
        try {
            letterService.clearLetters(UserContext.getCurrentUser().getId(),type);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("error");
        }
        return jsonResult;
    }

}
